package com.pidan.thread;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.pidan.pojo.Product;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.pidan.util.IOutil.output;

/**
 * 导入商品类
 */
public class ImportProductThread implements Runnable {


    public void start() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        try {
            System.out.println("开始导入商品-------------");
            //设置导入参数
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            List<Product> list = ExcelImportUtil.importExcel(new File("F:/tbk/2021-03-28 20_19_51-2021-03-28.xls"), Product.class, params);
            System.out.println("导入商品完成-------------");
            System.out.println("开始下载图片-------------");
            String filePath = "F:/tbk/img/" + date + "/";
            list.forEach(product -> {
                        try {
                            //downloadUsingStream(product.getImgURL(), filePath+product.getProductId()+".jpg");
                            product.setImgURL(filePath + product.getProductId() + ".jpg");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println(product.toString());

                    }
            );

            File path = new File(filePath);
            if (!path.exists()) {
                path.mkdir();
            }
            output(list);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void downloadUsingStream(String urlStr, String file) throws IOException {

        URL url = new URL(urlStr);

        BufferedInputStream bis = new BufferedInputStream(url.openStream());

        FileOutputStream fis = new FileOutputStream(file);

        byte[] buffer = new byte[1024];

        int count = 0;

        while ((count = bis.read(buffer, 0, 1024)) != -1) {
            fis.write(buffer, 0, count);

        }

        fis.close();

        bis.close();

    }

    public static void main(String[] args) {
        new ImportProductThread().start();
    }
}
